package com.sdc.autohome.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Base64;

public class AutohomeTripleDES {
	public static final String KEY_ALGORITHM = "DESede";

	public static final byte[] CRYPTO_KEY = new byte[] { 0x61, 0x75, 0x74, 0x6F, 0x68, 0x6F, 0x6D, 0x65, 0x63, 0x6F,
			0x6F, 0x70, 0x65, 0x72, 0x61, 0x74, 0x65, 0x6F, 0x70, 0x65, 0x6E, 0x61, 0x70, 0x69 };
	public static final byte[] CRYPTO_IV = new byte[] { 0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD,
			(byte) 0xEF };
	
	public static final String CIPHER_ALGORITHM_CBC = "DESede/CBC/PKCS5Padding";

	private SecretKey secretKey;
	private Cipher cipher;
	
	
	
	public AutohomeTripleDES()  throws Exception {
		cipher=Cipher.getInstance(CIPHER_ALGORITHM_CBC);
		secretKey = new SecretKeySpec(CRYPTO_KEY, "DESede");
	}

	public String EncryptUrl(String url,String username,String password) throws Exception{
		String[] urls=url.split("[?]");
		String querystring="";
		if(urls.length==2){
			querystring=urls[1];
		}
		String md5string=Md5(querystring,username);
		return Base64.getEncoder().encodeToString(encrypt(username+":"+password+":"+md5string));
	}
	
	public String Md5(String querystring,String username) throws Exception{
		MessageDigest md = MessageDigest.getInstance("MD5");
		String input=querystring+"&key="+username;
		md.update(input.getBytes());
		byte[] thedigest = md.digest();
		StringBuffer sb=new StringBuffer();  
        for(int i=0;i<thedigest.length;i++){ 
            int v=thedigest[i]&0xff;  
            if(v<16){  
                sb.append(0);  
            }  
            sb.append(Integer.toHexString(v));  
        }
        return sb.toString();
	}
	
	public byte[] encrypt(String str) throws Exception {
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(CRYPTO_IV));
		return cipher.doFinal(str.getBytes());
	}
}